<template>
	<onez-view class="background"
		:style="{ opacity: opacity, width: width + 'px', height: height + 'px', backgroundImage: bgPic ? 'url(' + bgPic + ')' : 'none' }">
		<slot :paddings="paddings"></slot>
	</onez-view>
</template>

<script>
	import onezView from '../onez-view/onez-view.vue'
	export default {
		name: 'onez-background',
		components: {
			onezView
		},
		data() {
			return {
				tmpId: 'canvas' + (Math.random() + '').split('.')[1],
				ready: false,
				pic: null,
				bgPic: null,
				opacity: 0,
				width: 100,
				height: 100,
				canvas: null,
				paddings: {},
				ctx: null,
				pics: {},
				img: null,
				image: null,
				file: null,
				margins: {}
			};
		},
		props: {
			resid: {
				type: String,
				default: null
			},
			size: {
				type: String,
				default: null
			},
			margin: {
				type: String,
				default: null
			},
			padding: {
				type: String,
				default: null
			}
		},
		mounted() {
			this.init();
		},
		watch: {
			size() {
				this.draw();
			}
		},
		methods: {
			loadImage() {
				let that = this;
				return new Promise((resolve, reject) => {
					if (that.image) {
						resolve(that.image);
						return;
					}
					var img = new Image();
					img.onload = function() {
						that.image = img;
						resolve(that.image);
					};
					img.setAttribute('crossOrigin', '*');
					img.src = this.pic;
				});
			},
			downImage() {
				let that = this;
				return new Promise((resolve, reject) => {
					if (that.file) {
						resolve(that.file);
						return;
					}
					uni.downloadFile({
						url: this.pic,
						success: res => {
							that.file = res.tempFilePath;
							resolve(that.file);
						}
					});
				});
			},
			toUrl(type) {
				let that = this;
				return new Promise((resolve, reject) => {
					if (type == 'h5') {
						var dataurl = that.canvas.toDataURL('image/png');
						resolve(dataurl);
						/*
						var arr = dataurl.split(',');
						var mime = arr[0].match(/:(.*?);/)[1];
						var bstr = atob(arr[1]);
						var n = bstr.length;
						var u8arr = new Uint8Array(n);
						while (n--) {
						  u8arr[n] = bstr.charCodeAt(n);
						}
						var blob = new Blob([u8arr], { type: mime });
						resolve(window.URL.createObjectURL(blob));
						*/
						return;
					}
					uni.canvasToTempFilePath({
						canvasId: this.tmpId,
						success: function(res) {
							resolve(res.tempFilePath);
						},
						fail: function(res) {
							resolve(null);
						}
					});
				});
			},
			async init() {
				let info = {};
				let hashArr = [];						
				var zoom = 1;
				if (this.resid) {
					hashArr.push(this.resid);
				}
				if (this.size) {
					hashArr.push(this.size);
				}
				let hash = hashArr.join('|');
				if (!this.$game.cacheBackgrounds) {
					this.$game.cacheBackgrounds = {};
				}
				if (!this.$game.cacheBackgrounds[hash]) {
					if (this.resid) {
						info = await this.$game.hook(this, 'res', {
							resid: this.resid
						});
						this.pic = info.pic;
						this.bgPic = info.pic;
					}
					if (this.size) {
						info.size = this.size;
					}
					if (this.margin) {
						info.margin = this.margin;
					}
					if (this.padding) {
						info.padding = this.padding;
					}
					if (this.pic) {
						this.img = await this.$game.getImageInfo(this.pic);
					}
					if (info.size) {
						let t = info.size.split(',');
						this.width = parseInt(t[0]);
						this.height = parseInt(t[1]);
					}
					let {
						width,
						height
					} = this;
					var base_width = width;
					var base_height = height;
					if (info.margin) {
						let t = info.margin.split(',');
						if (t.length == 3) {
							t = [t[0], t[1], t[2], t[1]];
						} else if (t.length == 2) {
							t = [t[0], t[1], t[0], t[1]];
						} else if (t.length == 1) {
							t = [t[0], t[0], t[0], t[0]];
						}
						if (t.length == 4) {
							let img = this.img;

							if (width < img.width || height < img.height) {
								zoom = Math.max(img.width / width, img.height / height);
								width = Math.floor(width * zoom);
								height = Math.floor(height * zoom);
								this.width = width;
								this.height = height;
							}
							console.log(width, height);

							let margins = {};
							margins.top = parseInt(t[0]);
							margins.right = parseInt(t[1]);
							margins.bottom = parseInt(t[2]);
							margins.left = parseInt(t[3]);
							margins.width = this.width - margins.left - margins.right;
							margins.height = this.height - margins.top - margins.bottom;
							this.margins = margins;
							await this.draw();
							this.width = base_width;
							this.height = base_height;
						}
					}
					// console.log('bg info.padding ==> ', info.padding, typeof(info.padding))
					if (info.padding) {
						let t = info.padding.split(',');
						if (t.length == 4) {
							t = [t[0], t[1], t[2], t[3]];
						} else if (t.length == 2) {
							t = [t[0], t[1], t[0], t[1]];
						} else if (t.length == 1) {
							t = [t[0], t[0], t[0], t[0]];
						}
						t[0] = parseInt(t[0]);
						t[1] = parseInt(t[1]);
						t[2] = parseInt(t[2]);
						t[3] = parseInt(t[3]);
						t[0] /= zoom;
						t[1] /= zoom;
						t[2] /= zoom;
						t[3] /= zoom;
						let paddings = {};
						paddings.top = parseInt(t[0]);
						paddings.right = parseInt(t[1]);
						paddings.bottom = parseInt(t[2]);
						paddings.left = parseInt(t[3]);
						paddings.width = this.width - paddings.left - paddings.right;
						paddings.height = this.height - paddings.top - paddings.bottom;
						this.paddings = paddings;
						console.log('bg paddings ==> ', this.paddings)
					}
					this.$game.cacheBackgrounds[hash] = {
						pic: this.pic,
						bgPic: this.bgPic,
						margins: this.margins,
						paddings: this.paddings,
						width: this.width,
						height: this.height
					};
					console.log('bg if ==> ', info, this.paddings)
				} else {
					let {
						pic,
						bgPic,
						margins,
						paddings,
						width,
						height
					} = this.$game.cacheBackgrounds[hash];
					this.pic = pic;
					this.bgPic = bgPic;
					this.margins = margins;
					this.paddings = paddings;
					this.width = width;
					this.height = height;
				}
				this.$game.tween(this, 0.3, {
					opacity: 1,
					ease: 'linear.in'
				});
				this.ready = true;
				this.$emit('ready', this.paddings);
			},
			async drawByH5() {
				let img = await this.loadImage();
				let margins = this.margins;
				this.bgPic = null;
				if (!this.ctx) {
					this.canvas = document.createElement('canvas');
					this.canvas.width = this.width;
					this.canvas.height = this.height;
					this.ctx = this.canvas.getContext('2d');
				}
				await this.$game.wait(this);
				await this.$game.delay(0.1);
				this.ctx.clearRect(0, 0, this.width, this.height);
				//左上
				this.ctx.drawImage(img, 0, 0, margins.left, margins.top, 0, 0, margins.left, margins.top);
				//上
				this.ctx.drawImage(img, margins.left, 0, img.width - margins.left - margins.right, margins.top, margins
					.left, 0, margins.width, margins.top);
				//右上
				this.ctx.drawImage(img, img.width - margins.right, 0, margins.right, margins.top, this.width - margins
					.right, 0, margins.right, margins.top);
				//中左
				this.ctx.drawImage(img, 0, margins.top, margins.left, img.width - margins.top - margins.bottom, 0,
					margins.top, margins.left, margins.height);
				//中
				this.ctx.drawImage(
					img,
					margins.left,
					margins.top,
					img.width - margins.left - margins.right,
					img.height - margins.top - margins.bottom,
					margins.left,
					margins.top,
					margins.width,
					margins.height
				);
				//中右
				this.ctx.drawImage(
					img,
					img.width - margins.right,
					margins.top,
					margins.left,
					img.height - margins.top - margins.bottom,
					this.width - margins.right,
					margins.top,
					margins.left,
					margins.height
				);

				//左下
				this.ctx.drawImage(img, 0, img.height - margins.bottom, margins.left, margins.bottom, 0, this.height -
					margins.bottom, margins.left, margins.bottom);
				//下
				this.ctx.drawImage(
					img,
					margins.left,
					img.height - margins.bottom,
					img.width - margins.left - margins.right,
					margins.bottom,
					margins.left,
					this.height - margins.bottom,
					margins.width,
					margins.bottom
				);
				//右下
				this.ctx.drawImage(
					img,
					img.width - margins.right,
					img.height - margins.bottom,
					margins.right,
					margins.bottom,
					this.width - margins.right,
					this.height - margins.bottom,
					margins.right,
					margins.bottom
				);
				let url = await this.toUrl('h5');
				if (url) {
					this.bgPic = url;
				} else {
					this.bgPic = this.pic;
				}
			},
			async drawByUni() {
				let img = this.img;
				let file = await this.downImage();

				let margins = this.margins;
				this.bgPic = null;
				if (!this.ctx) {
					//this.ctx = uni.createCanvasContext(this.tmpId, this);
					this.ctx = await this.$game.$stage.canvas(this.width, this.height);
					await this.$game.wait(this);
					await this.$game.delay(0.2);
				}
				this.ctx.clearRect(0, 0, this.width, this.height);
				//左上
				this.ctx.drawImage(file, 0, 0, margins.left, margins.top, 0, 0, margins.left, margins.top);
				//上
				this.ctx.drawImage(file, margins.left, 0, img.width - margins.left - margins.right, margins.top,
					margins.left, 0, margins.width, margins.top);
				//右上
				this.ctx.drawImage(file, img.width - margins.right, 0, margins.right, margins.top, this.width - margins
					.right, 0, margins.right, margins.top);
				//中左
				this.ctx.drawImage(file, 0, margins.top, margins.left, img.height - margins.top - margins.bottom, 0,
					margins.top, margins.left, margins.height);
				//中
				this.ctx.drawImage(
					file,
					margins.left,
					margins.top,
					img.width - margins.left - margins.right,
					img.width - margins.top - margins.bottom,
					margins.left,
					margins.top,
					margins.width,
					margins.height
				);
				//中右
				this.ctx.drawImage(
					file,
					img.width - margins.right,
					margins.top,
					margins.left,
					img.height - margins.top - margins.bottom,
					this.width - margins.right,
					margins.top,
					margins.left,
					margins.height
				);

				//左下
				this.ctx.drawImage(file, 0, img.height - margins.bottom, margins.left, margins.bottom, 0, this.height -
					margins.bottom, margins.left, margins.bottom);
				//下
				this.ctx.drawImage(
					file,
					margins.left,
					img.height - margins.bottom,
					img.width - margins.left - margins.right,
					margins.bottom,
					margins.left,
					this.height - margins.bottom,
					margins.width,
					margins.bottom
				);
				//右下
				this.ctx.drawImage(
					file,
					img.width - margins.right,
					img.height - margins.bottom,
					margins.right,
					margins.bottom,
					this.width - margins.right,
					this.height - margins.bottom,
					margins.right,
					margins.bottom
				);
				await this.$game.wait(this);
				await this.waitDraw();
				let url = await this.$game.$stage.canvasUrl();
				if (url) {
					this.bgPic = url;
				} else {
					this.bgPic = this.pic;
				}
			},
			waitDraw() {
				return new Promise((resolve, reject) => {
					this.ctx.draw(false, resolve);
				});
			},
			async draw() {
				if (!this.margins.width) {
					this.bgPic = this.pic;
				}
				if (this.$game.inUniApp()) {
					await this.drawByUni();
				} else {
					await this.drawByH5();
				}
			}
		}
	};
</script>

<style scoped>
	.background {
		position: absolute;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		display: block;
	}

	.item {
		position: absolute;
	}

	.t,
	.c,
	.b {
		width: 100%;
	}

	.item .item {
		top: 0;
	}
</style>